package services

import (
	"fmt"
	"my-new-gin/entitys"
	"my-new-gin/utils"
)

type ServiceUser struct {

}

func (this *ServiceUser) InsertUser(user *entitys.EntityUser) error {
	db, err := utils.GetMysqlConn()
	if err != nil {
		return err
	}
	count := 0
	db.Model(&entitys.EntityUser{}).Where("username = ?", user.Username).Count(&count)
	fmt.Println("count-->> ",count)
	if count > 0 {
		return fmt.Errorf("%s already exists",user.Username)
	}
	db.Model(&entitys.EntityUser{}).Create(user)
	return nil
}

func (this *ServiceUser) DeleteUserByUid(uid int) error {
	return nil
}

func (this *ServiceUser) DeleteUserByUsername(username string) error {
	return nil
}

func (this *ServiceUser) UpdateUserByUid(uid int, user *entitys.EntityUser) error {
	return nil
}

func (this *ServiceUser) UpdateUserByUsername(username string, user *entitys.EntityUser) error {
	return nil
}

func (this *ServiceUser) SelectUserByUid(uid int) (*entitys.EntityUser, error) {
	return nil, nil
}

func (this *ServiceUser) SelectUserByUsername(username string) (*entitys.EntityUser, error) {
	db, err := utils.GetMysqlConn()
	if err != nil {
		return nil, err
	}
	user := new(entitys.EntityUser)
	db.Model(&entitys.EntityUser{}).Where(entitys.EntityUser{Username:username}).First(user)
	if user == nil {
		return nil, fmt.Errorf("%s not exist",username)
	}
	return user, nil
}

func (this *ServiceUser) SelectUserByUsernameAndPassword(username, password string) (*entitys.EntityUser, error) {
	user, err := this.SelectUserByUsername(username)
	if err != nil {
		return nil, err
	}
	if user.Password != password {
		return nil, fmt.Errorf("password error")
	}
	return user, nil
}

func (this *ServiceUser) SelectUserList(conditions *entitys.EntityUser) ([]*entitys.EntityUser, error) {
	db, err := utils.GetMysqlConn()
	if err != nil {
		return nil, err
	}
	users := make([]*entitys.EntityUser,0)
	db.Model(&entitys.EntityUser{}).Where(conditions).Find(&users)
	return users, err
}
